package com.javasm.dao.Impl;

import com.javasm.Utils.JDBCHealper;
import com.javasm.dao.userDao;
import com.javasm.entity.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class userDaoImpl implements userDao {
    @Override
    public User getUserByNameAndPassword(String username, String password) {
        //通过jdbc链接数据库
        Connection connection = JDBCHealper.getConn();
        User user = null;
        //给数据库传报文
         String sql = "SELECT * FROM  user WHERE username =? AND  `password` = ?";
        PreparedStatement preparedStatement = null;
        try {
             preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,username);
            preparedStatement.setString(2,password);

            //3发送给MySQL
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()){
                int id = resultSet.getInt("id");
                String username1 = resultSet.getString("username");
                int age = resultSet.getInt("age");

                String password1 = resultSet.getString("password");
                 user = new User(id,username1,age,password1);
            }



        } catch (SQLException e) {
            throw new RuntimeException(e);
        }


        return user;
    }


    @Override
    public List<User> listuser() {
        //通过jdbc链接数据库
        Connection connection = JDBCHealper.getConn();
        List<User> listuser = new ArrayList<>();
        //给数据库传报文
        String sql = "SELECT * FROM  user";
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = connection.prepareStatement(sql);

            //3发送给MySQL
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()){
                int id = resultSet.getInt("id");
                String username1 = resultSet.getString("username");
                int age = resultSet.getInt("age");

                String password1 = resultSet.getString("password");
                User   user = new User(id,username1,age,password1);
                listuser.add(user);
            }



        } catch (SQLException e) {
            throw new RuntimeException(e);
        }


        return listuser;
    }
    }

